﻿using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using IndexMarkSilverlightClient.Classes;
using IndexMarkSilverlightClient.IndexMarkServiceReference;
using SharedCode.Controls;


namespace IndexMarkSilverlightClient.Views.Controls.ReportsControls
{
    public partial class IndexList : UserControl, INotifyPropertyChanged
    {
        IndexMarkServiceReference.IndexMarkServiceClient client =
            new IndexMarkServiceClient();

        private int _IDTerm;

        public int IDTerm
        {
            get { return _IDTerm; }
            set { _IDTerm = value; }
        }

        ObservableCollection<int> Cats = new ObservableCollection<int>();
        ObservableCollection<int> Teahers = new ObservableCollection<int>();
        ObservableCollection<int> Chars = new ObservableCollection<int>();
        ObservableCollection<IndexRow> indexes = new ObservableCollection<IndexRow>();

        private bool GroupByFaculty = false;
        private bool GroupByKafedra = false;
        private bool GroupByPosition = false;


        public PagedCollectionView GroupedIndexes
        {
            get
            {
                PagedCollectionView ind = new PagedCollectionView(this.indexes);
                ind.GroupDescriptions.Clear();
                if (GroupByFaculty)
                {
                    PropertyGroupDescription pg = new PropertyGroupDescription("Resp.Department.Parent.Abbriviation");
                    ind.GroupDescriptions.Add(pg);
                }
                if (GroupByKafedra)
                {
                    PropertyGroupDescription pg = new PropertyGroupDescription("Resp.Department.Abbriviation");
                    ind.GroupDescriptions.Add(pg);
                }
                if (GroupByPosition)
                {
                    PropertyGroupDescription pg = new PropertyGroupDescription("Position");
                    ind.GroupDescriptions.Add(pg);
                }
                int index = 0;
                foreach (IndexRow IR in ind)
                {
                    IR.OrderField = ++index;
                }
                return ind;
            }
        }

        public IndexList(IndexStrategyType strategy = IndexStrategyType.PPS)
        {
            StrategyType = strategy;
            InitializeComponent();
            Loaded += new RoutedEventHandler(IndexListLoaded);
        }

        void IndexListLoaded(object sender, RoutedEventArgs e)
        {
            var vm = MainPage.ViewModel;
            //var vm = (((((((this.Parent as Grid).Parent as Grid).Parent as ReportsMain).Parent as Frame).Parent as Border).Parent as Grid).Parent as MainPage).ViewModel;
            vm.SelectTerm -= ViewModel_SelectTerm;
            vm.SelectTerm += ViewModel_SelectTerm;
            vm.SelectTermInit();
            client.GetIndexes2Completed += (s_, e_) =>
            {
                indexes = e_.Result;
                this.DataContext = GroupedIndexes;
                loadingBar.Visibility = Visibility.Collapsed;
            };
            client.GetIndexes2Async(IDTerm, Cats, Teahers, Chars, IndexListType.Compact, StrategyType);
        }

        void ViewModel_SelectTerm(object sender, SelectTermEventsArgs e)
        {
            IDTerm = e.SelectTerm.IDTerm;
            client.GetIndexes2Async(IDTerm, Cats, Teahers, Chars, IndexListType.Compact, StrategyType);
        }

        private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            (IndexGrid.ItemsSource as PagedCollectionView).Filter = (obj) =>
            {
                return String.IsNullOrEmpty((sender as TextBox).Text) ||
                    (obj as IndexRow).Resp.Person.LastName.ToLower().Contains(
                        (sender as TextBox).Text.ToLower());
            };
        }

        private void CheckBox_Checked(object sender, RoutedEventArgs e)
        {
            GroupByFaculty = (sender as CheckBox).IsChecked.Value;
            IndexGrid.DataContext = GroupedIndexes;
        }

        private void CheckBox_Checked_1(object sender, RoutedEventArgs e)
        {
            GroupByKafedra = (sender as CheckBox).IsChecked.Value;
            IndexGrid.DataContext = GroupedIndexes;
        }

        private void CheckBox_Checked_2(object sender, RoutedEventArgs e)
        {
            GroupByPosition = (sender as CheckBox).IsChecked.Value;
            IndexGrid.DataContext = GroupedIndexes;
        }


        public event PropertyChangedEventHandler PropertyChanged;
        private IndexStrategyType StrategyType;

        private void IndexGrid_LoadingRowGroup(object sender, DataGridRowGroupHeaderEventArgs e)
        {
            e.RowGroupHeader.PropertyNameVisibility = Visibility.Collapsed;
        }

        private void HyperlinkButton_Click(object sender, RoutedEventArgs e)
        {
            IndexRow IR = IndexGrid.SelectedItem as IndexRow;
            ReportsMain.ShowLidia(IR, _IDTerm);
            //(((this.Parent as Grid).Parent as Grid).Parent as ReportsMain).NavigateToLIDIA(IR, _IDTerm);
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            ExportToExel(indexes);
        }

        void ExportToExel(ObservableCollection<IndexRow> indexRows)
        {

            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "Простой файл электронных таблиц | *.csv";
            if (sfd.ShowDialog().Value)
                using (StreamWriter SW = new StreamWriter(sfd.OpenFile(), CConst.Encoding))
                {
                    SW.Write("№;");
                    SW.Write("ФИО;");
                    SW.Write("Кафедра;");
                    SW.Write("Должность;");
                    SW.Write("Итоговый индекс;");
                    SW.Write("Р1;");
                    SW.Write("Р2;");
                    SW.Write("Р3;");
                    SW.Write("Р4;");
                    SW.Write("Р5;");
                    SW.Write("Р6;");
                    SW.Write("Индекс гармонии;");
                    SW.Write("Индекс лидерства;");
                    SW.WriteLine();

                    foreach (IndexRow row in indexRows)
                    {
                        SW.Write(row.OrderField + ";");
                        SW.Write(row.Resp.Person + ";");
                        SW.Write(row.Resp.Department.Abbriviation + ";");
                        SW.Write(row.Position + ";");
                        SW.Write(row.Index + ";");
                        foreach (var sectionIndex in row.SectionIndex)
                        {
                            SW.Write(sectionIndex.Index + ";");
                        }
                        SW.Write(row.IndexHarmony + ";");
                        SW.Write(row.IndexLider + ";");
                        SW.WriteLine();
                    }

                    SW.Close();
                }
        }
    }
}